#include <string.h>
#include <dirent.h>
#include "esp_lvgl_port.h"
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "file_iterator.h"
#include "jpeg_decoder.h"


#include "image_ui.h"
#include "main_ui.h"
#include "md_images.h"
#include "func_pin_image.h"
#include "md_languages.h"
#include "sd_card.h"

static const char *TAG = "image_viewer";

#define IMAGE_FILE_PATH SD_MOUNT_POINT "/image" // 图片文件路径

// 声明字体
LV_FONT_DECLARE(myFont);
LV_FONT_DECLARE(lv_font_montserrat_14);

// 定义最大图片数量
#define MAX_IMAGES 50
#define ZOOM_STEP  0.2f

// 全局变量
static char *image_list[MAX_IMAGES] = { 0 };
static int image_count = 0;
static int current_image = 0;
static float current_zoom = 1.0f;
static lv_obj_t *img_obj = NULL;
//static lv_obj_t *img_obj_old = NULL;
static lv_obj_t *img_root = NULL;
static lv_obj_t *label_info = NULL;
static lv_obj_t *control_panel = NULL; // 新增：控制面板容器

// 图像解码相关变量
static lv_img_dsc_t *decoded_img_dsc = NULL;

// 清除所有资源
static void cleanup_resources(void)
{
    // 释放图片列表
    for (int i = 0; i < image_count; i++) {
        if (image_list[i]) {
            heap_caps_free(image_list[i]);
            image_list[i] = NULL;
        }
    }
    image_count = 0;

    // 释放图像描述符
    if (decoded_img_dsc) {
        if (decoded_img_dsc->data) {
            heap_caps_free((void *)decoded_img_dsc->data);
        }
        heap_caps_free(decoded_img_dsc);
        decoded_img_dsc = NULL;
    }
}

void exit_image_ui(lv_obj_t *root)
{
    // 先清理资源
    cleanup_resources();

    // 卸载SD卡
    bsp_sdcard_unmount();

    // 切换到主界面
    switch_to_main_screen();

    // 删除界面对象
    if (root) {
        lv_obj_del(root);
        root = NULL;
    }
}

// 手势事件回调
static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        lv_dir_t dir = lv_indev_get_gesture_dir(indev);

        // 右划或上划退出
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            exit_image_ui(e->target);
        }
    }
}

// 扫描图片文件
static void scan_image_files(const char *path)
{
    ESP_LOGI(TAG, "Scanning for images in: %s", path);

    DIR *dir = opendir(path);
    if (!dir) {
        ESP_LOGE(TAG, "Failed to open directory: %s", path);
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL && image_count < MAX_IMAGES) {
        const char *ext = strrchr(entry->d_name, '.');
        if (ext) {
            if (strcasecmp(ext, ".bmp") == 0 ||
                strcasecmp(ext, ".png") == 0 ||
                strcasecmp(ext, ".jpg") == 0 ||
                strcasecmp(ext, ".jpeg") == 0) {
                // 分配内存并构建完整路径
                char *full_path = heap_caps_malloc(strlen(path) + strlen(entry->d_name) + 2,
                                                   MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
                if (!full_path) {
                    ESP_LOGE(TAG, "Failed to allocate memory for path");
                    continue;
                }

                sprintf(full_path, "%s/%s", path, entry->d_name);
                image_list[image_count++] = full_path;
                ESP_LOGI(TAG, "Found image: %s", full_path);
            }
        }
    }

    closedir(dir);
    ESP_LOGI(TAG, "Found %d images", image_count);
}

// // 图像解码回调函数，用于释放资源
// static void img_del_cb(lv_event_t *e)
// {
//     lv_event_code_t code = lv_event_get_code(e);

//     if (code == LV_EVENT_DELETE) {
//         // 释放图像描述符
//         if (decoded_img_dsc) {
//             if (decoded_img_dsc->data) {
//                 heap_caps_free((void *)decoded_img_dsc->data);
//             }
//             heap_caps_free(decoded_img_dsc);
//             decoded_img_dsc = NULL;
//         }
//     }
// }

// 解码并显示图像
static bool decode_and_display_image(const char *image_path)
{

    /*先释放之前的图像描述符*/
    if (decoded_img_dsc) {
        if (decoded_img_dsc->data) {
            heap_caps_free((void *)decoded_img_dsc->data);
        }
        heap_caps_free(decoded_img_dsc);
        decoded_img_dsc = NULL;
    }
    /* 解码并显示图像  */
    const char *ext = strrchr(image_path, '.');
    if (!ext) {
        ESP_LOGE(TAG, "No file extension: %s", image_path);
        return false;
    }

    FILE *fp = fopen(image_path, "rb");
    if (!fp) {
        ESP_LOGE(TAG, "Failed to open file: %s", image_path);
        return false;
    }

    // 获取文件大小
    fseek(fp, 0, SEEK_END);
    size_t file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    // 读取文件数据
    uint8_t *file_data = heap_caps_malloc(file_size, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
    if (!file_data) {
        ESP_LOGE(TAG, "Failed to allocate memory for file data");
        fclose(fp);
        return false;
    }

    size_t bytes_read = fread(file_data, 1, file_size, fp);
    fclose(fp);

    if (bytes_read != file_size) {
        ESP_LOGE(TAG, "Failed to read file");
        heap_caps_free(file_data);
        return false;
    }

    // 根据文件扩展名选择解码器
    esp_err_t ret = ESP_FAIL;
    uint8_t *out_buf = NULL;
    size_t out_size = 0;
    uint32_t width = 0, height = 0;

    if (strcasecmp(ext, ".jpg") == 0 || strcasecmp(ext, ".jpeg") == 0) {
        // JPEG解码
        esp_jpeg_image_cfg_t jpeg_cfg = {
            .indata = file_data,
            .indata_size = file_size,
            .out_format = JPEG_IMAGE_FORMAT_RGB565,
            .out_scale = JPEG_IMAGE_SCALE_0,
            .flags = {
                .swap_color_bytes = 1,
            }
        };

        esp_jpeg_image_output_t outinfo;
        ret = esp_jpeg_get_image_info(&jpeg_cfg, &outinfo);
        if (ret == ESP_OK) {
            width = outinfo.width;
            height = outinfo.height;
            out_size = width * height * 2; // RGB565 = 2 bytes per pixel
            
            out_buf = heap_caps_malloc(out_size, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
            if (out_buf) {
                jpeg_cfg.outbuf = out_buf;
                jpeg_cfg.outbuf_size = out_size;
                ret = esp_jpeg_decode(&jpeg_cfg, &outinfo);
            } else {
                ret = ESP_FAIL;
            }
        }
    } else {
        ESP_LOGE(TAG, "Unsupported image format: %s", ext);
        heap_caps_free(file_data);
        return false;
    }

    // 释放文件数据
    heap_caps_free(file_data);

    // 检查解码结果
    if (ret != ESP_OK || !out_buf) {
        ESP_LOGE(TAG, "Image decode failed: %d", ret);
        if (out_buf) {
            heap_caps_free(out_buf);
        }
        return false;
    }

    // 创建LVGL图像描述符
    decoded_img_dsc = heap_caps_malloc(sizeof(lv_img_dsc_t), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
    if (!decoded_img_dsc) {
        ESP_LOGE(TAG, "Failed to allocate image descriptor");
        heap_caps_free(out_buf);
        return false;
    }

    decoded_img_dsc->header.cf = LV_IMG_CF_TRUE_COLOR;
    decoded_img_dsc->header.always_zero = 0;
    decoded_img_dsc->header.reserved = 0;
    decoded_img_dsc->header.w = width;
    decoded_img_dsc->header.h = height;
    decoded_img_dsc->data_size = out_size;
    decoded_img_dsc->data = out_buf;

    // 创建图像对象
   // img_obj = lv_img_create(img_root);
    lv_img_set_src(img_obj, decoded_img_dsc);
  //  lv_obj_add_event_cb(img_obj, img_del_cb, LV_EVENT_DELETE, NULL);
    
    // 确保图片在控制面板下方
    lv_obj_move_background(img_obj);

    return true;
}

// 显示当前图片
static void show_current_image(void)
{
    if (image_count == 0 || current_image < 0 || current_image >= image_count)
        return;

    // // 清除当前图片
    // if (img_obj) {
    //     img_obj_old = img_obj;
    //     lv_obj_del(img_obj_old);
    //     img_obj = NULL;
    // }

    // 释放之前的图像描述符
    if (decoded_img_dsc) {
        if (decoded_img_dsc->data) {
            heap_caps_free((void *)decoded_img_dsc->data);
        }
        heap_caps_free(decoded_img_dsc);
        decoded_img_dsc = NULL;
    }

    const char *image_path = image_list[current_image];
    
    // 解码并显示图像
    if (!decode_and_display_image(image_path)) {
        ESP_LOGE(TAG, "Failed to display image: %s", image_path);
        
        // 创建错误提示
        lv_obj_t *label_err = lv_label_create(img_root);
        lv_label_set_text(label_err, "图片加载失败");
        lv_obj_set_style_text_color(label_err, lv_color_white(), 0);
        lv_obj_set_style_text_font(label_err, &myFont, 0);
        lv_obj_align(label_err, LV_ALIGN_CENTER, 0, 0);
        return;
    }

    lv_obj_align(img_obj, LV_ALIGN_CENTER, 0, 0);
    lv_img_set_zoom(img_obj, (uint16_t)(current_zoom * 256));

    // 更新信息标签
    char info[100];
    const char *filename = strrchr(image_list[current_image], '/');
    filename = filename ? filename + 1 : image_list[current_image];

    snprintf(info, sizeof(info), "%d/%d: %s (Zoom: %.1fx)",
             current_image + 1, image_count, filename, current_zoom);
    lv_label_set_text(label_info, info);
    
    // 确保控制面板在最前面
    lv_obj_move_foreground(control_panel);
}

// 按钮事件回调
static void btn_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *btn = lv_event_get_target(e);

    if (code == LV_EVENT_CLICKED) {
        const char *btn_text = lv_label_get_text(lv_obj_get_child(btn, 0));

        if (strcmp(btn_text, LV_SYMBOL_LEFT) == 0) {
            // 上一张图片
            if (current_image > 0) {
                current_image--;
                current_zoom = 1.0f; // 重置缩放
                show_current_image();
            }
        } else if (strcmp(btn_text, LV_SYMBOL_RIGHT) == 0) {
            // 下一张图片
            if (current_image < image_count - 1) {
                current_image++;
                current_zoom = 1.0f; // 重置缩放
                show_current_image();
            }
        } else if (strcmp(btn_text, LV_SYMBOL_PLUS) == 0) {
            // 放大
            current_zoom += ZOOM_STEP;
            if (current_zoom > 3.0f)
                current_zoom = 3.0f;
            if (img_obj) {
                lv_img_set_zoom(img_obj, (uint16_t)(current_zoom * 256));
            }

            // 更新信息标签
            char info[100];
            const char *filename = strrchr(image_list[current_image], '/');
            filename = filename ? filename + 1 : image_list[current_image];

            snprintf(info, sizeof(info), "%d/%d: %s (Zoom: %.1fx)",
                     current_image + 1, image_count, filename, current_zoom);
            lv_label_set_text(label_info, info);
        } else if (strcmp(btn_text, LV_SYMBOL_MINUS) == 0) {
            // 缩小
            current_zoom -= ZOOM_STEP;
            if (current_zoom < 0.5f)
                current_zoom = 0.5f;
            if (img_obj) {
                lv_img_set_zoom(img_obj, (uint16_t)(current_zoom * 256));
            }

            // 更新信息标签
            char info[100];
            const char *filename = strrchr(image_list[current_image], '/');
            filename = filename ? filename + 1 : image_list[current_image];

            snprintf(info, sizeof(info), "%d/%d: %s (Zoom: %.1fx)",
                     current_image + 1, image_count, filename, current_zoom);
            lv_label_set_text(label_info, info);
        }
    }
}

lv_obj_t *create_image_ui(void)
{
    // 创建根容器（全屏黑色背景）
    img_root = lv_obj_create(NULL);
    if (!img_root)
        return NULL;

    lv_obj_set_size(img_root, lv_pct(100), lv_pct(100));
    lv_obj_set_style_bg_color(img_root, lv_color_black(), LV_PART_MAIN);
    lv_obj_add_event_cb(img_root, event_handler, LV_EVENT_GESTURE, NULL);

    // 挂载SD卡
    esp_err_t ret = bsp_sdcard_mount();
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "SD card mount failed");
        // 创建错误提示界面
        lv_obj_t *label_err = lv_label_create(img_root);
        lv_label_set_text(label_err, "SD卡挂载失败");
        lv_obj_set_style_text_color(label_err, lv_color_white(), 0);
        lv_obj_set_style_text_font(label_err, &myFont, 0);
        lv_obj_align(label_err, LV_ALIGN_CENTER, 0, 0);
        return img_root;
    }

    // 扫描图片文件
    scan_image_files(IMAGE_FILE_PATH);

    // 创建控制面板（半透明背景）
    control_panel = lv_obj_create(img_root);
    lv_obj_set_size(control_panel, lv_pct(100), LV_SIZE_CONTENT);
    lv_obj_set_style_bg_color(control_panel, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(control_panel, LV_OPA_50, 0); // 50%不透明度
    lv_obj_set_style_border_width(control_panel, 0, 0);
    lv_obj_set_style_pad_all(control_panel, 5, 0);
    lv_obj_align(control_panel, LV_ALIGN_BOTTOM_MID, 0, 0);

    // 创建信息标签（放在控制面板内）
    label_info = lv_label_create(control_panel);
    lv_label_set_long_mode(label_info, LV_LABEL_LONG_SCROLL_CIRCULAR);
    lv_obj_set_width(label_info, lv_pct(100));
    lv_obj_set_style_text_color(label_info, lv_color_white(), 0);
    lv_obj_set_style_text_font(label_info, &lv_font_montserrat_14, 0);
    lv_obj_align(label_info, LV_ALIGN_TOP_MID, 0, 0);

    // 创建控制按钮
    static lv_style_t style_btn;
    lv_style_init(&style_btn);
    lv_style_set_bg_color(&style_btn, lv_color_white());
    lv_style_set_bg_opa(&style_btn, LV_OPA_70); // 70%不透明度
    lv_style_set_radius(&style_btn, 20);
    lv_style_set_text_color(&style_btn, lv_color_black());
    lv_style_set_text_font(&style_btn, &lv_font_montserrat_14);
    lv_style_set_pad_all(&style_btn, 10);

    // 创建按钮容器
    lv_obj_t *btn_container = lv_obj_create(control_panel);
    lv_obj_remove_style_all(btn_container); // 移除默认样式
    lv_obj_set_size(btn_container, lv_pct(100), LV_SIZE_CONTENT);
    lv_obj_set_flex_flow(btn_container, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(btn_container, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_align(btn_container, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_set_style_pad_top(btn_container, 10, 0);

    // 上一张按钮
    lv_obj_t *btn_prev = lv_btn_create(btn_container);
    lv_obj_add_style(btn_prev, &style_btn, 0);
    lv_obj_set_size(btn_prev, 50, 40);
    lv_obj_add_event_cb(btn_prev, btn_event_cb, LV_EVENT_ALL, NULL);

    lv_obj_t *label_prev = lv_label_create(btn_prev);
    lv_label_set_text(label_prev, LV_SYMBOL_LEFT);
    lv_obj_center(label_prev);

    // 缩小按钮
    lv_obj_t *btn_zoom_out = lv_btn_create(btn_container);
    lv_obj_add_style(btn_zoom_out, &style_btn, 0);
    lv_obj_set_size(btn_zoom_out, 50, 40);
    lv_obj_add_event_cb(btn_zoom_out, btn_event_cb, LV_EVENT_ALL, NULL);

    lv_obj_t *label_zoom_out = lv_label_create(btn_zoom_out);
    lv_label_set_text(label_zoom_out, LV_SYMBOL_MINUS);
    lv_obj_center(label_zoom_out);

    // 放大按钮
    lv_obj_t *btn_zoom_in = lv_btn_create(btn_container);
    lv_obj_add_style(btn_zoom_in, &style_btn, 0);
    lv_obj_set_size(btn_zoom_in, 50, 40);
    lv_obj_add_event_cb(btn_zoom_in, btn_event_cb, LV_EVENT_ALL, NULL);

    lv_obj_t *label_zoom_in = lv_label_create(btn_zoom_in);
    lv_label_set_text(label_zoom_in, LV_SYMBOL_PLUS);
    lv_obj_center(label_zoom_in);

    // 下一张按钮
    lv_obj_t *btn_next = lv_btn_create(btn_container);
    lv_obj_add_style(btn_next, &style_btn, 0);
    lv_obj_set_size(btn_next, 50, 40);
    lv_obj_add_event_cb(btn_next, btn_event_cb, LV_EVENT_ALL, NULL);

    lv_obj_t *label_next = lv_label_create(btn_next);
    lv_label_set_text(label_next, LV_SYMBOL_RIGHT);
    lv_obj_center(label_next);
    // 创建图像对象
    img_obj = lv_img_create(img_root);
    //lv_img_set_src(img_obj, decoded_img_dsc);
    //lv_obj_add_event_cb(img_obj, img_del_cb, LV_EVENT_DELETE, NULL);
    // 确保图片在控制面板下方
    lv_obj_move_background(img_obj);
    // 如果没有找到图片，显示提示信息
    if (image_count == 0) {
        lv_obj_t *label_no_img = lv_label_create(img_root);
        lv_label_set_text(label_no_img, "未找到图片!\n请在/sdcard/image目录添加图片");
        lv_obj_set_style_text_color(label_no_img, lv_color_white(), 0);
        lv_obj_set_style_text_font(label_no_img, &myFont, 0);
        lv_obj_align(label_no_img, LV_ALIGN_CENTER, 0, 0);
    } else {
        // 显示第一张图片
        current_image = 0;
        current_zoom = 1.0f;
        show_current_image();
    }

    return img_root;
}